/*
 * JGroup example
 */
package org.sup.hi;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;

public class AutoChat extends ReceiverAdapter{
	JChannel channel;
	Address address;
	String user_name = System.getProperty("user.name","n/a");
	
	private void start() throws Exception{
		channel = new JChannel();
		channel.setReceiver(this);
		channel.connect("ChatCluster");
		farcry();
	}
	
	// @ @
	private void farcry() {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			private int times = 5;
			@Override
			public void run() {
				try {
					times--;
					if(times<0){
						channel.close();
						this.cancel();
						System.out.println("Exit");
						System.exit(0);
					}else{
						String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
						String line = "messeage from " + user_name + " " + timeStamp;
						Message msg = new Message(null, null, line);
						channel.send(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 0, 1000);
	}
	
	@Override
	public void receive(Message msg) {
		System.out.println(msg.getSrc()+": "+msg.getObject());
	}

	// Called when a new instance joins the cluster
	// or an existing instance leaves
	@Override
	public void viewAccepted(View view) {
		System.out.println("** view: "+ view);
	}

	public static void main(String[] args) throws Exception {
		new AutoChat().start();
	}

}
